/*

MAIN CUSTOM SCRIPTS FILE

Author -  0
Contact - 

*/

//configuration
var autoImprovePerformance = true; //automatically switch off demanding tasks on mobile devices
var animationDuration = 600; //animation speed
var easing = "easeInOutQuad"; //animation easing type
var parallax = true; //toggle parallax
var parallaxSpeed = 0.4; //parallax effect speed
var animated = true; //toggle animation
var fetchAmount = 2; //how many blog posts to fetch each time the load more... button is pressed

//variables
var navHeight = $("nav").height();
var current;
var fragment = 0;
var animationDelayCount = 0;

$(document).ready(function(){

	$('.flexslider').flexslider({
		animation: "slide"
	});

	//update parallax on window resize
	if(autoImprovePerformance)
		improvePerformance();

	//bypass the 'rel' validation error
	$('a[data-rel]').each(function() {
		$(this).attr('rel', $(this).data('rel'));
	});

	//start the colorbox plugin
	$(".colorbox").colorbox({returnFocus:true, trapFocus:true, overlayClose:true, speed: animationDuration});

	// Cache selectors
	var topMenu = $("nav"),
	topMenuHeight = topMenu.outerHeight()+15,
	// All list items
	menuItems = topMenu.find("a:not(.ignore)"),
	// Anchors corresponding to menu items
	scrollItems = menuItems.map(function(){
	  var item = $($(this).attr("href"));
	  if (item.length) { return item; }
	});

	//start the hoverfold plugin if supported by browser
	Modernizr.load({
		test: Modernizr.csstransforms3d && Modernizr.csstransitions,
		yep : ['js/jquery.hoverfold.js'],
		nope: 'css/fallback.css',
		callback : function( url, result, key ) {
			
			$('#portfolio').hoverfold();
			
		}
	});
	
	//clear the message form on clear button click
	$(document).on("click", ".clear-button", function(evt){
	
		var form = $("#form");
	
		form.addClass("animated shake");
		setTimeout(function(){
					
			form.find(".form-control").each(function(){
		
				$(this).val('');
			
			});
			
			form.removeClass("animated shake");
			
		}, animationDuration);
	
	});
	
	//send the message form on submit button click
	$(document).on("click", ".submit-button", function(evt){
	
		var form = $("#form");
		$("#form-message").css("opacity","1").html('<img src="img/ajax.gif" alt="universal-preloader"/> Processing...');
		
		
		setTimeout(function(){
		
			//try to send the mail
			mailForm(function(){
			
				form.find(".form-control").each(function(){
		
					$(this).val('');
				
				});
			
			});
			
		}, animationDuration*2);
	
	});
	
	//ajax load the portfolio item contents on portfolio item link click
	$(document).on("click", "#portfolio a", function(evt){
	
		var $this = $(this);
		var $portfolioContent = $("#portfolio-content");
		var $portfolioContentPosition = Math.round($("#section6").offset().top);
		var animationD = animationDuration;
	
		evt.preventDefault();
		evt.stopPropagation();
		
		$('html, body').stop().animate({"scrollTop": $portfolioContentPosition +"px"}, {duration:animationDuration, easeing:easing, start:function(){$portfolioContent.css("display","block");} ,complete:function(){
		
			//prevents double even firing - DO NOT REMOVE THIS LINE
			if (this.nodeName == "BODY") {return;}
		
			if($portfolioContent.hasClass("open"))
				$portfolioContent.removeClass("open");
			else
				animationD = 0;
			
			setTimeout(function(){
		
				$portfolioContent.ajaxLoad($this.attr("href"), false, function(){
		
					$portfolioContent.addClass("open");
					setTimeout(function(){
					
						$(window).trigger("scroll");
						
					}, animationDuration);
				
				});
			
			}, animationD);
		
		}});
	
	});
	
	//on portfolio-content close button click
	$(document).on("click", ".navigation i.glyphicon-remove", function(evt){
	
		var $portfolioContent = $("#portfolio-content");
	
		$portfolioContent.removeClass("open");
		setTimeout(function(){
					
			$portfolioContent.css("display","none").find(".container").empty();
			
		}, animationDuration);
	
	});
	
	//on blog-content prev, next button click
	$(document).on("click", ".load-more", function(evt){
	
		var $this = $(this);
		var $blogContentTemp = $("#blog-temp");
		var $blogContent = $("#blog");
		var $loadMoreButton = $(".load-more");
		evt.preventDefault();
		evt.stopPropagation();
	
		if(!$this.hasClass("disabled")){
			
			$loadMoreButton.html("<img src='img/ajax.gif' alt='universal-preloader'/></span>");
			
			setTimeout(function(){
			
				$blogContentTemp.ajaxLoad($this.attr("href"), false, function(){
				
					var $elements = $blogContentTemp.find(".item");
					
					$elements.removeAttr("style");
					
					$blogContent.append($elements.slice(fragment, fragment+fetchAmount));
					$blogContentTemp.empty();
					
					$loadMoreButton.html("Load more ...");
					
					fragment += fetchAmount;
					
					if(fragment >= $elements.length)
						$loadMoreButton.addClass("disabled").html("No more posts to load!!!");
									
				});
			
			}, animationDuration);
		
		}
	
	});
	
	//on portfolio-content prev, next button click
	$(document).on("click", ".navigation a.next, .navigation a.prev", function(evt){
	
		var $this = $(this);
		var $portfolioContent = $("#portfolio-content");
		evt.preventDefault();
		evt.stopPropagation();
		
		$portfolioContent.removeClass("open");
				
		setTimeout(function(){
		
			$portfolioContent.ajaxLoad($this.attr("href"), false, function(){
	
				$portfolioContent.addClass("open");
				setTimeout(function(){
				
					$(window).trigger("scroll");
					
				}, animationDuration);
			
			});
		
		}, animationDuration);
	
	});
	
	//start the coreSlider plugin
	$("section.section5").coreSlider(6000, "fadeInLeft", "fadeOutRight");
	$("section.section1").coreSlider(6000, "fadeInDown", "fadeOutUp");

	//start the preloader plugin
	$(document).preloader("image-preloader", startPreloader);

	//start the scroller plugin
	$("nav, #scroll-down").scroller(animationDuration*2, easing);

	//update the hero segments on window resize
	var lazyLayout = _.debounce(updateHeroContainer, 500);
	$(window).resize(lazyLayout);
	
	updateHeroContainer();
	
	// Bind to scroll - add throttle
	var throttled = _.throttle(checkActiveMenu, 100);
	$(window).scroll(throttled);
	
	checkActiveMenu();
	
	//nav menu animations
	$("nav ul li a").on("mouseenter", function(){
	
		$(this).addClass("open");
	
	});
	
	$("nav ul li a").on("mouseleave", function(){
	
		$(this).removeClass("open");
	
	});
	
	startParallax();
	
	if(!animated)
		$(".circle.notready").each(function(){
		
			var span = $(this).children("span");
			span.text(addCommas(span.text()));
		
		});
	
	//filter the portfolio
	$('#portfolio').mixitup({
	
		targetSelector: '.mix',
		filterSelector: '.filter',
		sortSelector: '.sort',
		buttonEvent: 'click',
		effects: ['fade','rotateZ', 'scale'],
		listEffects: null,
		easing: 'smooth',
		layoutMode: 'grid',
		targetDisplayGrid: 'block',
		targetDisplayList: 'block',
		gridClass: '',
		listClass: '',
		transitionSpeed: animationDuration,
		showOnLoad: 'all',
		sortOnLoad: false,
		multiFilter: false,
		filterLogic: 'or',
		resizeContainer: true,
		minHeight: 0,
		failClass: 'fail',
		perspectiveDistance: '3000',
		perspectiveOrigin: '50% 50%',
		animateGridList: true,
		onMixLoad: null,
		onMixStart: null,
		onMixEnd: null
		
	});
	
	function checkActiveMenu(){
	   // Get container scroll position
	   var fromTop = $(this).scrollTop();

	   // Get id of current scroll item
	   var cur = scrollItems.map(function(){
		 if ($(this).offset().top < fromTop + $(window).height())
		   return this;
	   });
	   		 
	   // Get the id of the current element
	   cur = cur[cur.length-1];
	   var id = cur && cur.length ? cur[0].id : "";
	   // Set/remove active class
	   menuItems
		 .parent().removeClass("active")
		 .end().filter("[href=#"+id+"]").parent().addClass("active");
	}
	
	function startPreloader(){
	
		//make sure all images are fully loaded
		var images = $("#image-preloader img");
		var nimages = images.length;
		var interval;
		var counter = 0;
		var prev = 0;
		var percentage;
		
		images.load(function(){updatePreloader();});
		
		function updatePreloader(){
			
			percentage = Math.round(((counter + 1) / nimages) * 100);

			if(percentage >= 100)
				percentage = 100;

			interval = setInterval(function(){
			
				if(prev <= percentage)
					$("#percentage").html((prev++)+"%");
				else{
				
					clearInterval(interval);
					prev = percentage;
				
				}
			
			}, 200);
			
			counter++;
			
			if(counter == nimages)
				endPreloading();
		
		}
	
	}
	
	function startParallax(){
	
		//start the parallax plugin
		if(parallax == true){
		
			$("#section1").parallax("50%", parallaxSpeed);
			$("#section3").parallax("50%", parallaxSpeed);
			$("#section5").parallax("50%", parallaxSpeed);
			$("#section7").parallax("50%", parallaxSpeed);
			
		}
	
	}

});

//remove the preloader
function endPreloading(){

	setTimeout(function(){$("#universal-preloader").css("opacity","0");}, animationDuration / 2);
	
	if(animated){
		
		setTimeout(function(){
		
			addAnimationIfInView();
			//add the animation when the content comes into view
			var throttled2 = _.throttle(addAnimationIfInView, 50);
			$(window).scroll(throttled2);
		
		}, animationDuration * 2);
			
	}
	else{
	
		$(".a").removeClass("a");
		$(".skillset").each(function(){
		
			var perc = $(this).text();
			$(this).css({"width":perc, "opacity":"1"});
		
		});
		
	}
	
	setTimeout(function(){
			
		$("#universal-preloader").remove();
		$("#image-preloader").remove();
			
	}, animationDuration * 2);
	
}

//animate the elements within the viewport
function addAnimationIfInView(){

	var counter = 1;
	animationDelayCount = 0;

	$(".a").each(function(){
	
		var thiss = $(this);
	
		if(isScrolledIntoView(thiss)){
		
			animationDelayCount++;
		
			if(!thiss.hasClass("animated"))
				setTimeout(function(){thiss.addClass("animated").removeClass("a");}, 100 * animationDelayCount);
				
		}
			
	});
	
	$(".skillset").each(function(){
			
		var thiss = $(this);
	
		if(isScrolledIntoView(thiss)){
		
			var perc = thiss.text();
			animationDelayCount++;
			
			setTimeout(function(){thiss.css({"width":perc, "opacity":"1"});}, 100 * animationDelayCount);
		
		}
				
	});
	
	$(".circle.notready").each(function(){
	
		var thiss = $(this);
		
		if(isScrolledIntoView(thiss)){
		
			thiss.removeClass("notready");
		
			var span = thiss.children("span");
			var spanText = span.text();
			var interval;
		
			span.text("0");
			
			interval = setInterval(function(){
			
				if(counter <= spanText){
				
					span.text(addCommas(counter));
					counter++;
				
				}
				else
					clearInterval(interval);
			
			}, counter*20);
		
		}
	
	});

}

//check if element is in view
function isScrolledIntoView(elem)
{

    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).outerHeight(true);

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
	
}

//update the hero containers
function updateHeroContainer(){

	var hero = $(".hero");
	var heroContainer = $(".hero .container");
	heroContainer.css("margin-top", "-"+ heroContainer.height() / 2 +"px");
	hero.css("height", $(window).height() + "px");

}

//handle mail verification and sending
function mailForm(callback){
	
	var flag = "";
	var msgPosition = Math.round($("#section9").offset().top);
	
	//get all required elements
	$("#form").find("*.required").each(function(){
		
		$(this).removeClass("error");
		
		//if any of them is null
		if($(this).val().length == 0){
		
			$(this).addClass("error");
			
			//validation error
			flag += "<span class='glyphicon glyphicon-remove-sign'></span> Form field <strong>"+$(this).attr("id")+"</strong> is empty, please provide a value<br />";
			
		}
																		 
	});

	//email validation
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var emailValue = $("#email").val();

	if(!emailReg.test(emailValue))
		flag += "<span class='glyphicon glyphicon-remove-sign'></span> Not a valid <strong>email</strong>! Please try again<br />";
		
	if(flag=="") {
		
			//submit form via ajax
			var dataString = 'name='+ $("#yourname").val() + '&email=' + $("#email").val() + '&message=' + $("#message").val();
			//alert (dataString);return false;  
			$.ajax({  
			  type: "POST",  
			  url: "php/mail.php",  
			  data: dataString,
			  error: function(xhr, ajaxOptions, thrownError){

				$("#contact-notice").html("Error "+xhr.status+" - "+thrownError+" | Please contact our <strong>support team</strong> with this code!");

			  }
			  }).done(function(data){

				var data = data.split("^");
				//get and filter return data

				//change message type on success or error
				if(data[0] == "ok")
					$("#form-message").addClass("ok");
				else
					$("#form-message").addClass("error");

				$('html, body').stop().animate({"scrollTop": msgPosition +"px"}, {duration:animationDuration, easeing:easing, complete:function(){$("#form-message").html('<div class="alert alert-success"><span class="glyphicon glyphicon-send"> MESSAGE SENT</span>'+""+'</div>'); callback();}});

			  });  
			
	}
	else {
	
		//validation errors, alert
		$('html, body').stop().animate({"scrollTop": msgPosition +"px"}, {duration:animationDuration, easeing:easing, complete:function(){$("#form-message").html('<div class="alert alert-danger">'+flag+'</div>');}});
		
	}

}

//improve performance
function improvePerformance(){

	if($(window).width() < 768){

		parallax = false;
		animated = false;
		
	}

}

//add commas to numbers
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}